package com.yoyo.yyadsdk.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;
import com.yoyo.yyadsdk.api.IConfigApi;
import com.yoyo.yyadsdk.bean.BaiduAddressBean;
import com.yoyo.yyadsdk.bean.Gps;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static android.app.ActivityThread.TAG;

public class BaiduAddressUtil {
    private LocationManager mLocationManager;

    public BaiduAddressUtil(Context context) {
        mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        getAddress(getLocation(context), context);
    }

    public Location getLocation(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return null;
            }
        }
        //查找服务信息
        Location gpsLocation = null;
        Location netLocation = null;
        if (netWorkIsOpen()) {
            //2000代表每2000毫秒更新一次，5代表每5秒更新一次
            mLocationManager.requestLocationUpdates("network", 2000, 5, locationListener);
            netLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }

        if (gpsIsOpen()) {
            mLocationManager.requestLocationUpdates("gps", 2000, 5, locationListener);
            gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }

        if (gpsLocation == null && netLocation == null) {
            return null;
        }
        if (gpsLocation != null && netLocation != null) {
            if (gpsLocation.getTime() < netLocation.getTime()) {
                return netLocation;
            } else {
                return gpsLocation;
            }
        }
        if (gpsLocation == null) {
            return netLocation;
        } else {
            return gpsLocation;
        }
    }

    private boolean gpsIsOpen() {
        boolean isOpen = true;
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {//没有开启GPS
            isOpen = false;
        }
        return isOpen;
    }

    private boolean netWorkIsOpen() {
        boolean netIsOpen = true;
        if (!mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {//没有开启网络定位
            netIsOpen = false;
        }
        return netIsOpen;
    } //监听GPS位置改变后得到新的经纬度

    private LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.e("location", location.toString() + "....");
            // TODO Auto-generated method stub
            //获取国家，省份，城市的名称
//            getAddress(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    @SuppressLint("CheckResult")
    public void getAddress(@Nullable Location location, final Context context) {
        if (location == null) return;
        Log.e("location", location.toString());
        Gps gps = PositionUtil.gps84_To_bd09(location.getLatitude(), location.getLongitude());
        if (gps == null) return;
        Observable<BaiduAddressBean> baiduAddressBeanObservable = ApiManage.getInstance().getApi("http://api.map.baidu.com/", IConfigApi.class)
                .getLocation(gps.toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        if (context instanceof AppCompatActivity) {
            baiduAddressBeanObservable
                    .as(AutoDispose.<BaiduAddressBean>autoDisposable(AndroidLifecycleScopeProvider.from((LifecycleOwner) context, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(new Consumer<BaiduAddressBean>() {
                        @Override
                        public void accept(BaiduAddressBean responseBody) {
                            Log.e(TAG, responseBody.getResult().getAddressComponent().getCity() + responseBody.getResult().getAddressComponent().getCountry());
                            SpUtil.setCity(context, responseBody.getResult().getAddressComponent().getCity());
                            if (mLocationManager != null && locationListener != null)
                                mLocationManager.removeUpdates(locationListener);
                            if (mLocationManager != null)
                                mLocationManager = null;
                            if (locationListener != null)
                                locationListener = null;
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) {

                        }
                    });
        } else {
            baiduAddressBeanObservable.subscribe(new Consumer<BaiduAddressBean>() {
                @Override
                public void accept(BaiduAddressBean responseBody) {
                    Log.e(TAG, responseBody.getResult().getAddressComponent().getCity() + responseBody.getResult().getAddressComponent().getCountry());
                    SpUtil.setCity(context, responseBody.getResult().getAddressComponent().getCity());
                    if (mLocationManager != null && locationListener != null)
                        mLocationManager.removeUpdates(locationListener);
                    if (mLocationManager != null)
                        mLocationManager = null;
                    if (locationListener != null)
                        locationListener = null;
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable throwable) {

                }
            });
        }
    }
}
